//
//  VIPLatestTableViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/16.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let latestCellIdentifier = "VIPLatestCell"

struct VIPLatestItem {
  var dateString: String
  var albums: [Album]
}

class VIPLatestViewController: VIPChildViewController {

  // MARK: - IBOutlets
  
  @IBOutlet private weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  private var latestItems = [VIPLatestItem]()
  private var isFirstLoaded = true
  
  // MARK: - Private methods
  
  private func loadData() {
    API.shared.requestAPI (
      APIURLStrings.vipLatest,
      method: .get,
      header: API.shared.memeberHeader,
      successCallback: { json in
        if let itemObjects = json["latest"].arrayObject as? [[String: Any]] {
          // sync albums
          var albumObjects = [[String: Any]]()
          itemObjects.forEach {
            let albums = $0["albums"] as! [[String: Any]]
            albumObjects.append(contentsOf: albums)
          }
          
          EntityManager.sync (
            type: Album.self,
            rawObject: albumObjects,
            operations: [.update, .insert, .insertRelationships, .updateRelationships, .deleteRelationships],
            completion: { error, _ in
              if error == nil {
                // prepare latest items
                self.latestItems = [VIPLatestItem]()
                itemObjects.forEach {
                  let albums = $0["albums"] as! [[String: Any]]
                  let albumIDs = albums.map { $0["id"] as! Int }
                  let latestItem = VIPLatestItem (
                    dateString: $0["date"] as! String,
                    albums: EntityManager.fetch(Album.self, fetchType: .ids(albumIDs))!
                  )
                  self.latestItems.append(latestItem)
                }
                self.tableView.reloadData()
//                UIView.animate(withDuration: 0.3, animations: {
//                  self.tableView.alpha = 1
//                })
              }
          })
        }
    }) { message, code in
      loggingPrint("VIP latest data loading error. \(message)")
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    loadData()
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if isFirstLoaded {
      isFirstLoaded = false
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  override func prepareUI() {
    tableView.backgroundColor = .clear
    tableView.tableFooterView = UIView()
//    tableView.alpha = 0
  }
  
  override func getScrollView() -> UIScrollView {
    return tableView
  }
}

// MARK: - UITableViewDataSource

extension VIPLatestViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return latestItems.count
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let latestItem = latestItems[section]
    return latestItem.albums.count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: latestCellIdentifier, for: indexPath) as! VIPLatestCell
    let album = latestItems[indexPath.section].albums[indexPath.row]
    cell.prepare(album: album)
    return cell
  }
}

// MARK: - UITableViewDelegate

extension VIPLatestViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let album = latestItems[indexPath.section].albums[indexPath.row]
    let storyboard = UIStoryboard(name: "ContentBrowsing", bundle: nil)
    let albumDetailViewController = storyboard.instantiateViewController(withIdentifier: "AlbumDetailViewController") as! AlbumDetailViewController
    albumDetailViewController.albumIdentifier = Int(album.id)
    navigationController?.pushViewController(albumDetailViewController, animated: true)
    
    tableView.deselectRow(at: indexPath, animated: true)
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return VIPLatestCell.defaultHeight
  }
  
  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return latestItems[section].dateString
  }
}

// MARK: - UIScrollViewDelegate

extension VIPLatestViewController: UIScrollViewDelegate {
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    scrollViewDelegate?.vipChildViewController(self, didScroll: scrollView.contentOffset.y)
  }
}
